package com.sf.marathon.soul.service;

import java.util.Date;

import com.sf.marathon.soul.core.base.BusinessException;
import com.sf.marathon.soul.domain.ExpressGroup;
import com.sf.marathon.soul.domain.ProMarketBase;
import com.sf.marathon.soul.vo.ExpressGroupDetail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.sf.marathon.soul.core.base.BaseService;
import com.sf.marathon.soul.core.util.BeanMapper;
import com.sf.marathon.soul.dao.SenderGroupRelationMapper;
import com.sf.marathon.soul.domain.SenderExpressBase;
import com.sf.marathon.soul.domain.SenderGroupRelation;
import com.sf.marathon.soul.vo.SenderGroupVO;

/**
 * <p>
 * 寄件人与报名团关系 服务实现类
 * </p>
 *
 * @author mokeo
 * @since 2017-12-15
 */
@Service
public class SenderGroupRelationService extends BaseService<SenderGroupRelationMapper, SenderGroupRelation> {
    @Autowired
    private SenderExpressBaseService senderService;

    @Autowired
    private ExpressGroupService groupService;

    @Autowired
    private ExpressGroupDetailService detailService;

    @Autowired
    private ProMarketBaseService proMarketBaseService;

    public void join(SenderGroupVO vo) {

        if(checkGroupIsNotFinish(vo.getGroupId())){
            save(vo);
        }else{
            throw new BusinessException("对不起，该团已满，请加入下一轮的拼团");
        }
        // 判断团是否已经满
        ExpressGroupDetail detail = detailService.findOneById(vo.getGroupId());
        if(detail.getLeftNum().equals(1)){
            ExpressGroup group = (ExpressGroup)groupService.selectById(vo.getGroupId());
            group.setGroupStatus(ExpressGroup.STATUS_DONE);
            groupService.updateById(group);
            // 生成新团
            ProMarketBase m = (ProMarketBase) proMarketBaseService.selectById(group.getMaketId());
            groupService.generateGroup(m);

        }

    }

    private void save(SenderGroupVO vo){
        SenderExpressBase sender = BeanMapper.map(vo, SenderExpressBase.class);
        Wrapper ew = new EntityWrapper();
        ew.eq("user_id", vo.getUserId());
        senderService.delete(ew);
        senderService.insert(sender);

        SenderGroupRelation m = new SenderGroupRelation();
        m.setUserId(vo.getUserId());
        m.setGroupId(vo.getGroupId());
        m.setCreateTime(new Date());
        super.baseDao.insert(m);
    }

    private boolean checkGroupIsNotFinish(Long groupId){
        // 先判断团是否已经满了
        ExpressGroup group = (ExpressGroup)groupService.selectById(groupId);
        if(group != null){
            return ExpressGroup.STATUS_ING.equals(group.getGroupStatus());
        }else{
            throw new BusinessException("请先选择一个要拼的团");
        }
    }
}
